package features.advance.jdk.file;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * @author LIN
 * @date 2023-01-16 09:37
 */
@Slf4j
public class FileDemo {

    public static void main(String[] args) throws IOException {
        String fileName = createMoreFiles();
        File file = new File(fileName);
        boolean delete = file.delete();
        log.info("{}文件夹或者文件是否删除成功：{}",fileName,delete);

        Path path = Paths.get(fileName);
        try{
            Files.delete(path);
        }catch(Exception e){
            log.debug(e.getMessage());
        }

        Files.walkFileTree(path,new SimpleFileVisitor<Path>(){
            // 先去遍历删除文件
            @Override
            public FileVisitResult visitFile(Path file,
                                             BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                System.out.printf("文件被删除 : %s%n", file);
                return FileVisitResult.CONTINUE;
            }
            // 再去遍历删除目录
            @Override
            public FileVisitResult postVisitDirectory(Path dir,
                                                      IOException exc) throws IOException {
                Files.delete(dir);
                System.out.printf("文件夹被删除: %s%n", dir);
                return FileVisitResult.CONTINUE;
            }

        });

    }




    private static String createMoreFiles() throws IOException {
        String first = "D:\\data\\test1\\test2\\";
        Files.createDirectories(Paths.get(first+"test3\\test4\\test5\\"));
        Files.write(Paths.get(first+"test2.log"), "hello".getBytes());
        Files.write(Paths.get(first+"test3\\test3.log"), "hello".getBytes());
        return first;
    }



}
